#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include "gsm0710.h"

int open_serial(const char *name);/* @115200-8N1. return serial_fd */
extern void gsm0710_callback_reg_dft(struct gsm0710_context * ctx,int serial_fd);

int main(void)
{
    struct gsm0710_context *ctx;
    int serial_fd = open_serial("/dev/ttyUSB0");
    if(serial_fd<0){
        printf("Error: Canot open serial!\n");
        return -1;
    }

    printf("Open serial successful!\n");
    ctx=gsm0710_context_new();
    if(!ctx) {
        printf("Error: No enough memory!\n");
        close(serial_fd);
    	return -1;
    }
    gsm0710_callback_reg_dft(ctx,serial_fd);

    /* startup and open 2channel, one is for AT command,anther is for ppp */
    gsm0710_startup(ctx,1);	
    gsm0710_open_channel(ctx,1);
    gsm0710_open_channel(ctx,2);
    sleep(1); /* wait GPRS module respond */

    /* Send AT command */
    gsm0710_write_data(ctx,1,"AT\r",3);
    gsm0710_write_data(ctx,2,"AT\r",3);
    sleep(1);

    gsm0710_ready_read(ctx);

    /* shutdown and free memory */
    gsm0710_shutdown(ctx);
    gsm0710_context_free(ctx);
    close(serial_fd);

    return 0;
}

int open_serial(const char *name)
{
    int serial_fd;
    struct termios opt;

    serial_fd = open(name,O_RDWR);
    if(serial_fd<0) return serial_fd;

    tcgetattr(serial_fd,&opt);
    tcflush(serial_fd,TCIOFLUSH);

    cfsetispeed(&opt,B115200);
    cfsetospeed(&opt,B115200);
    opt.c_cflag &= ~CSIZE; /* 8bit data */
    opt.c_cflag |=  CS8;
    opt.c_cflag &= ~PARENB; /* no parity */
    opt.c_iflag &= INPCK;
    opt.c_cflag &= ~CSTOPB; /* 1 stop bit */

    /* set raw input, 1second timeout */
    opt.c_cflag |= (CLOCAL | CREAD);
    opt.c_lflag &= ~(ICANON | ECHO |ECHOE | ISIG);
    opt.c_oflag &= ~OPOST;
    opt.c_cc[VMIN]=0;
    opt.c_cc[VTIME]=10; 

    tcsetattr(serial_fd,TCSANOW,&opt);
    return serial_fd;
}

